-- JavaInterfaces
-- Created by chengb Nov/26/2015
-- 提供给Java调用的接口

local PURE_FILE = "JavaInterfaces";

-- Google账号验证成功的回调
function onGoogleConnected(param)
    local arr = string.explode(param, "|");
    local account = arr[1];
    local token   = arr[2];

    -- 设置G+账号登录信息
    local info = {
        ["account"] = account,
        ["extra"] = {
            ["3rdplatform"] = CHANNEL_GOOGLE,
            ["token"]       = token,
        },
    };
    set3rdAccountLoginInfo(CHANNEL_GOOGLE, info);

    -- 抛出G+账号登录事件
    trace("JavaInterfaces", "onGoogleConnected");
    EventMgr.fire(event.GOOGLE_CONNECTED, { ["loginInfo"] = info, });
end

-- Google连接失败
function onGoogleConnectError(param)
    trace(PURE_FILE, "onGoogleConnectError: "..param);
    EventMgr.fire(Event.GOOGLE_CONNECT_ERROR, param);
end

-- 请求谷歌登录相关权限被拒绝
function onGooglePermissionDenied()
    confirm2(CONFIRM_TYPE_OK, getLocStr("google_center_login_title"), getLocStr("google_permission_denied"), function() end);
end

-- 请求谷歌登录相关权限被拒绝，且用户勾选不再提示
function onGooglePermissionDisabled()
    confirm2(CONFIRM_TYPE_OK, getLocStr("google_center_login_title"), getLocStr("google_permission_disabled"), function() end);
end

-- GooglePlay购买失败的回调
function onGooglePurchaseFail(reason)
    EventMgr.fire(event.RECHARGE_FAIL);
end

-- facebook账号登录的回调
function onFacebookConnected(param)
    local arr = string.explode(param, "|");
    local account = arr[1];
    local token   = arr[2];

    -- 设置facebook账号登录信息
    local info = {
        ["account"] = account,
        ["extra"] = {
            ["3rdplatform"] = getFacebookChannelName(),
            ["token"]       = token,
        },
    };
    set3rdAccountLoginInfo(getFacebookChannelName(), info);

    -- 抛出facebook账号登录事件
    EventMgr.fire(event.FACEBOOK_CONNECTED, { ["loginInfo"] = info, });
end

-- facebook账号登录异常
function onFacebookLoginError(param)
    -- 弹提示
    showHint2(getLocStr("slime_note"), "Facebook login failed", true);
end

-- 充值扣款成功的事件回调（这里只是客户端扣款成功）
function onRechargeOk(param)
    trace("JavaInterfaces", "onRechargeOk: param = " .. tostring(param));

    local sku;
    local orderId;

    -- 如果是GooglePlay平台（非pt购买版本），需要记录订单号
    if PUBLISH_PLATFORM == PUBLISH_TYPE_GOOGLE_PLAY and
       not MarketM.isBuyGemByPt() then
        local info = string.parseJsonToTable(param);
        sku        = info.sku;
        orderId    = info.orderId;
    else
        sku = param;
    end
    ChargeM.rechargeHandle(sku, orderId);
end

-- 充值失败的事件回调
function onRechargeFail(sku)
    EventMgr.fire(event.RECHARGE_FAIL);
end

-- 充值交易完成的回调（此时已完成扣款，并且已将订单写入pdb数据库，客户端需要等待服务器通知到账）
function onRechargeTransFinish(sku)
    trace("JavaInterface", "onRechargeTransFinish:sku = %s", tostring(sku));
    EventMgr.fire(event.RECHARGE_TRANS_FINISH, { sku = sku, });
end

-- 批量查询商品的回调
function onBatchQuerySkuPrice(param)
    if param == "" then
        return;
    end

    local resultList = string.explode(param, "|");

    for _, str in pairs(resultList) do
        local arr = string.explode(str, "&");
        local sku   = arr[1];
        local price = arr[2];

        -- 如果是国内的平台，需要接上单位
        if not isOverseaPackage() then
            price = price .. getLocStr("yuan");
        else
            -- TODO 目前中文的'$'和英文版的'￥'显示有问题，故做如下处理
            local lang = getLang();
            if lang == "zh" then
                -- 替换美元符号
                price = changeDollerCharacter(price);
            elseif lang == "en" then
                -- 替换人民币符号
                price = string.gsub(price, "￥", "CNY");
            end
        end

        if sku ~= "" and price ~= "" then
            -- 记录价格
            MarketM.recordSkuPrice(sku, price);
        end
    end
end

-- 通知广告的准备状态
function onAdReadyState(state)
    local readyState = iif(state == "1", true, false);

    -- 通知广告是否就绪
    EventMgr.fire(event.AD_READY_STATE, { ["readyState"] = readyState });
end

-- 用户看完了奖励广告
function onRewardAdCompleted()
    -- 抛出广告播放完毕的事件
    EventMgr.fire(event.AD_COMPLETED);
end

-- 用户关闭广告屏幕
function onDismissAdScreen()
    EventMgr.fire(event.DISMISS_AD_SCREEN);
end

-- 用户点击了广告
function onClickAd()
    EventMgr.fire(event.CLICK_AD);
end

-- 广告渲染失败
function onAdRenderFailed()
    -- 通知服务器
    Operation.cmd_ad_render_failed();
end

-- facebook分享成功的回调
function onFBShareSucc(shareType)
    shareType = tonumber(shareType);

    -- 抛出分享成功的事件
    EventMgr.fire(event.FB_SHARE_SUCC, { ["shareType"] = shareType, });
end

-- 分享图片下载成功的回调
function onShareImageDownloaded()
    -- 抛出事件
    EventMgr.fire(event.SHARE_IMAGE_DOWNLOAD_SUCC);
end

-- 微博分享成功的回调
function onWeiboShareSucc(shareType)
    shareType = tonumber(shareType);

    -- 抛出分享成功的事件
    EventMgr.fire(event.WEIBO_SHARE_SUCC, { ["shareType"] = shareType, });
end

-- 显示FAQ失败的回调
function onShowFAQsError()
    -- 跳转至网页版
    showWebFAQs();
end

-- UC平台登录成功的回调
function onUCLoginSucc(param)
    local arr = string.explode(param, "|");
    local uid = arr[1];
    local sid = arr[2];

    local channel = CHANNEL_UC;

    local info = {
        ["account"] = uid,
        ["extra"] = {
            ["3rdplatform"] = channel,
            ["sid"]         = sid,
        },
    };
    set3rdAccountLoginInfo(channel, info);

    -- 抛出第三方账号登录事件
    EventMgr.fire(event.THIRD_ACCOUNT_LOGINED, { ["channel"] = channel, ["loginInfo"] = info, });
end

-- 渠道登录认证失败
function onChannelLoginFail(channel)
    EventMgr.fire(event.THIRD_ACCOUNT_LOGIN_FAIL, { ["channel"] = channel, });
end

--------------------
-- 渠道sdk初始化完毕
-- @param platfrom 运营平台
function onChannelSdkInited(platform)
    trace(PURE_FILE, "%s渠道sdk初始化完毕", platform);
    EventMgr.fire(event.CHANNEL_SDK_INITED, { ["platform"] = platform, });
end

-- 亚马逊账号登录成功
function onAmazonConnected(param)
    trace(PURE_FILE, "onAmazonConnected: param = " .. param);
    local jsonParam = string.parseJsonToTable(param);

    local account  = jsonParam.account;
    local token    = jsonParam.token;
    local agsReady = jsonParam.agsReady;  -- GameCircle是否准备完毕  "1"：是  "0"：否
    local channel  = CHANNEL_AMAZON;

    -- 设置账号登录信息
    local info = {
        ["account"] = account,
        ["extra"] = {
            ["3rdplatform"] = channel,
            ["token"]       = token,
        },
    };
    set3rdAccountLoginInfo(channel, info);

    -- 抛出第三方账号登录事件
    EventMgr.fire(event.THIRD_ACCOUNT_LOGINED, {
        ["channel"]   = channel,
        ["loginInfo"] = info,
        ["agsReady"]  = agsReady,
    });
end

-- 亚马逊GameCircle准备完毕
function onGameCircleReady()
    trace(PURE_FILE, "onGameCircleReady");
    EventMgr.fire(event.GAME_CIRCLE_READY);
end

-- 小米账号登录成功
function onMILogined(param)
    local arr = string.explode(param, "|");
    local uid = arr[1];
    local session = arr[2];

    local channel = CHANNEL_MI;

    -- 设置账号登录信息
    local info = {
        ["account"] = uid,
        ["extra"] = {
            ["3rdplatform"] = channel,
            ["session"]     = session,
            ["uid"]         = uid,
        },
    };
    set3rdAccountLoginInfo(channel, info);

    -- 抛出第三方账号登录事件
    EventMgr.fire(event.THIRD_ACCOUNT_LOGINED, { ["channel"] = channel, ["loginInfo"] = info, });
end

-- 退出游戏
function onExitGame()
    confirm2(CONFIRM_TYPE_OK_CANCEL, getLocStr("exit_game_title"), getLocStr("exit_game_confirm"), simpleExitSystem);
end

-- 微信分享成功的回调
function onWechatShareSucc(shareType)
    shareType = tonumber(shareType);

    trace("JavaInterface", "微信分享成功，类型：%d", shareType);

    -- 抛出分享成功的事件
    EventMgr.fire(event.WECHAT_SHARE_SUCC, { ["shareType"] = shareType, });
end

-- 往日志服务器上传java日志
function postJavaLogToServer(data)
    trace("JavaInterface", "postJavaLogToServer: data = %s", data);
    local url = SDK_ERROR_REPORT_URL;
    if url == "" then
        trace("JavaInterface", "尚未配置sdk异常上报地址");
        return;
    end

    local tinfo = string.parseJsonToTable(data);
    local tag   = tinfo.tag;  -- 标签
    local msg   = tinfo.msg;  -- 日志

    local account = AccountM.getGamingAccount() or "";

    local errorMsg = string.format("%s [%s][%s] %s", os.date(), account, tag, msg);
    postDataToRemoteHost(url, errorMsg);
end

-- 注销账号成功的回调
function onLogoutOk()
    -- 清除上次登录的渠道记录
    setLastAccountChannel("");
    EventMgr.fire(event.THIRD_ACCOUNT_LOGOUT);
end

-- 处理来至Java的请求
-- @brief 本函数可作为所有Java回调的入口
function handleJavaFuncRequest(param)
    trace(PURE_FILE, "handleJavaFuncRequest:param = %s", param);

    local arr = string.explode(param, "|");

    local funcName = arr[1];
    local funcArgs = arr[2];

    assert(type(funcName) == "string", "必须传入funcName");

    SdkMgr.handleJavaFuncRequest(funcName, funcArgs);
end